#!/usr/bin/python
#-*-coding: utf-8 -*-
u"""
Preferences widget for pyLot
  05-2009, Pierre Puiseux, Guillaume Baty,
Université de Pau et des Pays de l'Adour, INRIA
"""

#This file is part of pyLot library.
#
# pyLot is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# pyLot is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with pyLot.  If not, see <http://www.gnu.org/licenses/>.

__author__ = u'Pierre Puiseux, Guillaume Baty'
__copyright__ = u"Copyright 2011-2012 (C) andheo, Université de Pau et des Pays de l'Adour"
__credits__ = [u'Pierre Puiseux', u'Guillaume Baty']
__license__ = "GNU Lesser General Public License"

__all__ = [u'GuiMainManagerPrefs']

from Qt4 import QtGui
from Qt4.QtCore import (SIGNAL, QSize)


from pyLot.core import hardbook, get_data, Datum

from _pylot.qtgui.tools import (create_background_palette, generate_pyfile_from_uifile,
                                get_named_font)
from _pylot.qtgui.styles.policy import *
from _pylot.qtgui.styles.charformats import PYLOT_CHAR_FORMATS
from _pylot.qtgui.styles.colors import PYLOT_COLORS
from _pylot.qtgui.widgets.gui_typedchoosers import GuiPredefUnicodeChooser
from _pylot.qtgui.default.impl_widget import Widget

def make_tooltip (qcolor):
  color = u'%s, %s, %s' % (qcolor.red(), qcolor.green(), qcolor.blue())
  tooltip = u"""
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
<html><head><meta name="qrichtext" content="1" />
<style type="text/css">
  p, li { white-space: pre-wrap; }
  .bold {font-weight:700;}
  .color {background-color:rgb(%s);}
</style>
</head>
<body>
<p><span class="bold">Color: </span><span class="color">    </span><br />
<span class="bold">RGB:</span>%s</p>
</body>
</html>
""" % (color, color)
  return tooltip

generate_pyfile_from_uifile(__name__)
from designer._gui_mainmanager_prefs import Ui_GuiMainManagerPrefs
class GuiMainManagerPrefs(QtGui.QWidget, Widget, Ui_GuiMainManagerPrefs):
  def __init__(self, char_formats=PYLOT_CHAR_FORMATS,
               char_colors=PYLOT_COLORS):
    QtGui.QWidget.__init__(self)
    self.setupUi(self)
    Widget.__init__(self)

    self.char_formats = char_formats
    self.char_colors = char_colors

    self._color_dict = {u'fg':u'foreground', u'bg':u'background'}
    self._fg_color_buttons = {}
    self._bg_color_buttons = {}
    self._alpha_spin_boxes = {}

    self._state_buttons = {
      u'success':self.success,
      u'fail':self.fail,
      u'running':self.running}

    labels = [u'Style', u'Font', u'Color', u'Bg', u'Opacity']
    # for i18n extraction
    [tr_(u'Style'), tr_(u'Font'), tr_(u'Color'), tr_(u'Bg'), tr_(u'Opacity')]
    for j, key in enumerate(labels) :
      label = QtGui.QLabel(tr_(key))
      label.setObjectName(u"l_%s" % key)
      label.setSizePolicy(QSizePolicy(Maximum, Preferred))
      self.font_grid.addWidget(label, 0, j, 1, 1)

    for i, key in enumerate(self.char_formats) :
      # foreground
      label = QtGui.QLabel(tr_(key))
      label.setObjectName(u"l_%s" % key)
      label.setSizePolicy(QSizePolicy(Maximum, Preferred))
      self.font_grid.addWidget(label, 1 + i, labels.index(u'Style'), 1, 1)

      button = QtGui.QPushButton(tr_(u"Change Font"))
      button.setObjectName(key)
      button.setSizePolicy(QSizePolicy(Maximum, Preferred))
      self.connect(button, SIGNAL('clicked()'), self.changeFont)
      self.font_grid.addWidget(button, 1 + i, labels.index(u'Font'), 1, 1)

      button = self._createColorButton(key)
      self._fg_color_buttons[key] = button

      self.font_grid.addWidget(button, 1 + i, labels.index(u'Color'), 1, 1)

      # background
      button = self._createColorButton(key)
      self._bg_color_buttons[key] = button

      self.font_grid.addWidget(button, 1 + i, labels.index(u'Bg'), 1, 1)

      spin_box = QtGui.QSpinBox()
      spin_box.setObjectName(key)
      spin_box.setMaximum(255)
      opacity = self.char_formats[key].background().color().alpha()
      spin_box.setValue(opacity)
      spin_box.setSizePolicy(QSizePolicy(Maximum, Preferred))
      self._alpha_spin_boxes[key] = spin_box

      self.font_grid.addWidget(spin_box, 1 + i, labels.index(u'Opacity'), 1, 1)

    datum = Datum(u'level', unicode, self.handler.level,
      value_list=[u'user', u'devel', u'expert'],
      tooltip=tr_(u'Allow to change User Interface Level'),
      alias=tr_(u'User Interface Level'))
    self.user_level_chooser = GuiPredefUnicodeChooser(datum)
    self.layout_ui.addWidget(self.user_level_chooser)

    datum = Datum(u'display_level', unicode, self.handler.level,
      value_list=[u'silent', u'standard', u'verbose', u'debug'],
      tooltip=tr_(u'Allow to change level of verbosity (quantity of outputs)'),
      alias=tr_(u'Verbosity Level'))
    self.verbosity_level_chooser = GuiPredefUnicodeChooser(datum)
    self.layout_ui.addWidget(self.verbosity_level_chooser)

    self.append(self.user_level_chooser)
    self.append(self.verbosity_level_chooser)

    self._createActions()
    self._createConnexions()

  def _createActions(self):
    self.action_whatsthis = QtGui.QAction(self)

  def _createConnexions (self):
    self.connect(self.action_whatsthis, SIGNAL("triggered()"),
                 QtGui.QWhatsThis.enterWhatsThisMode)

    for button in self._fg_color_buttons.values() :
      self.connect(button, SIGNAL("clicked()"), self.changeFgColor)
    for button in self._bg_color_buttons.values() :
      self.connect(button, SIGNAL("clicked()"), self.changeBgColor)
    for spin_box in self._alpha_spin_boxes.values() :
      self.connect(spin_box, SIGNAL("editingFinished()"), self.changeBgAlpha)
    for button in self._state_buttons.values() :
      self.connect(button, SIGNAL("clicked()"), self.changeExampleBg)

  def changeFgColor (self):
    form = unicode(self.sender().objectName())
    brush = self.char_formats[form].foreground()
    color = QtGui.QColorDialog.getColor(brush.color())
    if color.isValid() :
      brush.setColor(color)
      self.char_formats[form].setForeground(brush)

      self.refreshFontDialog()

  def changeBgColor (self):
    form = unicode(self.sender().objectName())
    brush = self.char_formats[form].background()
    color = QtGui.QColorDialog.getColor(brush.color())
    alpha = self._alpha_spin_boxes[form].value()
    color.setAlpha(alpha)
    if color.isValid() :
      brush.setColor(color)
    self.char_formats[form].setBackground(brush)

    self.refreshFontDialog()

  def changeExampleBg (self):
    color_name = unicode(self.sender().objectName())
    color = self.char_colors[color_name]
    bg = create_background_palette(color)
    self.text_sample.setPalette(bg)

  def changeBgAlpha (self):
    form = unicode(self.sender().objectName())
    brush = self.char_formats[form].background()
    color = brush.color()
    alpha = self._alpha_spin_boxes[form].value()
    color.setAlpha(alpha)
    brush.setColor(color)
    self.char_formats[form].setBackground(brush)
    self.refreshFontDialog()

  def changeFont (self):
    name = unicode(self.sender().objectName())
    font, changed = QtGui.QFontDialog.getFont(get_named_font(name, self.char_formats))
    if changed :
      self.char_formats[name].setFont(font)
      self.writeExample()

  def writeExample (self):
    self.text_sample.clear()
    self.text_sample.setCurrentCharFormat(self.char_formats[u'title'])
    self.text_sample.insertPlainText(u'Launch CMake script (title)\n')
    std_text = (
    u'-- The C compiler identification is GNU',
    u'-- The CXX compiler identification is GNU',
    u'-- Check for working C compiler: /usr/bin/gcc')
    self.text_sample.setCurrentCharFormat(self.char_formats[u'std'])
    self.text_sample.insertPlainText(u'\n'.join(std_text))
    self.text_sample.setCurrentCharFormat(self.char_formats[u'warn'])
    self.text_sample.insertPlainText(u'\n## Process aborted by user\n')
    self.text_sample.setCurrentCharFormat(self.char_formats[u'info'])
    self.text_sample.insertPlainText(u"CMake execution time : 2.8947s")

  def _createColorButton (self, name):
    from spyderlib.widgets.colors import ColorButton
    button = ColorButton()
    button.setObjectName(name)
#    button.setMinimumSize(QSize(25, 25))
#    button.setMaximumSize(QSize(25, 25))
#    button.setIconSize(QSize(25, 25))
#    button.setSizePolicy(QSizePolicy(Fixed, Fixed))
    button.setFlat(True)
#    pixmap = QtGui.QPixmap(24, 24)
#    button.setIcon(QtGui.QIcon(pixmap))
    return button

  def _refresh (self):
    self.user_level_chooser.setValue(self.handler.level)
    self.verbosity_level_chooser.setValue(self.handler.io.level)
    self.refreshFontDialog()

  def refreshFontDialog (self):
    self.refreshStateButtons()
    self.refreshFontButtons()
    self.writeExample()

  def refreshStateButtons (self):
    for key, button in self._state_buttons.items() :
      color = self.char_colors[key]
      pixmap = QtGui.QPixmap(25, 25)
      pixmap.fill(color)
      button.setIcon(QtGui.QIcon(pixmap))

  def refreshFontButtons (self):

    for key, button in self._fg_color_buttons.items() :
      color = self.char_formats[key].foreground().color()
      pixmap = QtGui.QPixmap(25, 25)
      pixmap.fill(color)
      button.setIcon(QtGui.QIcon(pixmap))
      brush = self.char_formats[key].foreground()
      button.setToolTip(make_tooltip(brush.color()))

    for key, button in self._bg_color_buttons.items() :
      color = self.char_formats[key].background().color()
      button_color = self.char_formats[key].background().color()
      button_color.setAlpha(255)
      pixmap = QtGui.QPixmap(25, 25)
      pixmap.fill(button_color)
      button.setIcon(QtGui.QIcon(pixmap))
      brush = self.char_formats[key].background()
      self._alpha_spin_boxes[key].setValue(int(brush.color().alpha()))
      button.setToolTip(make_tooltip(brush.color()))

  def getUserLevelChooser(self):
    return self.user_level_chooser

  def getVerbosityLevelChooser(self):
    return self.verbosity_level_chooser

  def _translate (self):
    for spin_box in self._alpha_spin_boxes.values() :
      spin_box.setToolTip(tr_(u'[0-255]. 0 = transparent, 255 = opaque'))

    self._setTexts([
      (self.action_whatsthis, tr_(u'What\'s this ?')),
      ])

    self._setTexts([
      (self.action_whatsthis, tr_(u'Shift+F1')),
      ], field=u'shortcut')
    self.writeExample()

if __name__ == u"__main__":
  from Qt4.QtGui import QApplication
  app = QApplication([])

  prefs = GuiMainManagerPrefs()
  prefs.show()

  ret = app.exec_()
